const inquirer = require('inquirer')
const path = require('path')
const axios = require('axios')
const { resolve, log, successLog, errorLog } = require('../utils')
const jenkinsUserList = require('../api/jenkins.key')
module.exports = async function autoJenkis(program) {
  //查找配置文件的jenkis用户信息
  let jenkinsUser = jenkinsUserList.find((item) => {
    return item.author == program.author
  })

  if (!jenkinsUser || !jenkinsUser.author) {
    jenkinsUser = jenkinsUserList[0]
  }
  // console.log("jenkinsUser---->", jenkinsUser);
  let apiToken = program.token || jenkinsUser.token //个人的apitoken , 路径:jenkins界面右上角用户名->设置->添加新Token
  let author = program.author || jenkinsUser.author //用户名
  let project = program.project || 'vue-webim-test' // 项目名
  let host = program.host || jenkinsUser.host //地址栏目
  let http = jenkinsUser.http || 'https://'
  let headerStr = `${http}${author}:${apiToken}@${host}${project}/buildWithParameters`
  let triggerName = program.triggerName || 'jenikis@rfchina.com' //jenkins->项目->配置->构建触发器->触发远程构建->填写你的身份验证令牌
  let gitBranch = program.gitBranch || program.gitTagName || '*/dev_branch'
  let url = `${headerStr}?token=${triggerName}&GIT_BRANCH=${encodeURI(
    gitBranch
  )}`
  //uploadComponentName为要带过去的参数,可以去掉
  console.log(
    '执行构建地址--->',
    `${host}${project}/buildWithParameters?token=${triggerName}&GIT_BRANCH=${encodeURI(
      gitBranch
    )}`
  )
  // 触发更新
  // GET request for remote image in node.js
  axios({
    url,
    method: 'get',
  })
    .then(function (response) {
      console.log('触发更新--->', response.status)
      if (response.status == 201) {
        console.log('触发jenkins编译成功')
      } else {
        console.log('触发jenkins编译失败')
      }
    })
    .catch((err) => {
      console.log('触发jenkins编译失败', err)
      var cp = require('child_process')
      cp.exec(`start chrome ${url}`)
      setTimeout(() => {
        cp.exec(`close chrome ${url}`)
      }, 500)
    })
}
